package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-11-20 12:57
 * @Version
 **/
public class Server {
    private final ServerBootstrap bootstrap;
    
    private EventLoopGroup boosGroup;
    private EventLoopGroup workerGroup;
    
    private ChannelFuture channelFuture;
    
    
    public Server() {
        this.bootstrap = initialization();
    }
    
    public Server handler(ChannelInitializer<Channel> initializer) {
        this.bootstrap.handler(initializer);
        return this;
    }
    
    public Server childHandler(ChannelHandler handler) {
        this.bootstrap.childHandler(handler);
        return this;
    }
    
    public ChannelFuture bind(int port) {
        this.channelFuture = this.bootstrap.bind(port);
        return channelFuture;
    }
    
    public void closeChannelSync() {
        try {
            this.channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            this.boosGroup.shutdownGracefully();
            this.workerGroup.shutdownGracefully();
        }
    }
    
    private ServerBootstrap initialization() {
        // 创建接受请求工作线程组
        this.boosGroup = new NioEventLoopGroup(1);
        // 创建处理请求工作线程组
        this.workerGroup = new NioEventLoopGroup(10);
        // 初始化服务启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        return serverBootstrap;
    }
    
    
}
